﻿using Microsoft.AspNetCore.Mvc.Filters;
using JESAI.Core;
using JESAI.Core.Exceptions;
using JESAI.Core.Util.Helpers;
using JESAI.Framework.Mvc;

namespace JESAI.Framework.Filters;

/// <summary>
/// 异常处理过滤器
/// </summary>
public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
    private readonly ILogger<ExceptionHandlerAttribute> _logger;
    public ExceptionHandlerAttribute(ILogger<ExceptionHandlerAttribute> logger)
    {
        _logger= logger;
    }
    /// <summary>
    /// 异常处理
    /// </summary>
    /// <param name="context">异常上下文</param>
    public override void OnException(ExceptionContext context)
    {
        context.ExceptionHandled = true;
        context.HttpContext.Response.StatusCode = 200;
        if (context.Exception is Warning warning)
        {
            context.Result = !string.IsNullOrWhiteSpace(warning.Code)
                ? new ApiResult(Conv.ToInt(warning.Code), warning.GetPrompt())
                : new ApiResult(StatusCode.Fail, warning.GetPrompt());
        }
        else
        {
            _logger.LogError(context.Exception,"WebApi全局异常");
            _logger.LogError(context.Exception.GetRawException(), "WebApi全局异常");
            context.Result = new ApiResult(StatusCode.Fail, context.Exception.GetPrompt());
        }
    }
}